package com.fusetech.web.flow.controller.audit;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fusetech.flow.audit.domain.AuditProcess;
import com.fusetech.flow.audit.domain.AuditProcessAuditorRoleUser;
import com.fusetech.flow.audit.domain.AuditProcessForm;
import com.fusetech.flow.audit.service.AuditProcessAuditorRoleUserService;
import com.fusetech.flow.audit.service.AuditProcessFormService;
import com.fusetech.flow.audit.service.AuditProcessService;
import com.fusetech.flow.audit.service.dto.AuditProcessDTO;
import com.fusetech.flow.audit.service.mapstruct.AuditProcessWrapper;
import com.fusetech.os.core.query.QueryWrapperGenerator;
import com.fusetech.os.core.response.ResponseMessage;
import com.fusetech.os.core.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.alibaba.excel.util.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;

/**
 * 审核流程Controller
 * @author admin
 * @version 2023-05-06
 */

@Api(tags ="审核流程")
@RestController
@RequestMapping(value = "/erp/audit/auditProcess")
public class AuditProcessController {

	@Autowired
	private AuditProcessService auditProcessService;
	@Autowired
	private AuditProcessFormService auditProcessFormService;
	@Autowired
	private AuditProcessAuditorRoleUserService auditProcessAuditorRoleUserService;

	@Autowired
	private AuditProcessWrapper auditProcessWrapperImpl;

	/**
	 * 审核流程列表数据
	 */
	//@ApiLog("查询审核流程列表数据")
	@ApiOperation(value = "查询审核流程列表数据")
	//@PreAuthorize({"erp:audit:auditProcess:list"})
	@GetMapping("list")
	public ResponseEntity<?> list(AuditProcessDTO auditProcessDTO, Page<AuditProcessDTO> page) throws Exception {
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (auditProcessDTO, AuditProcessDTO.class);
		IPage<AuditProcessDTO> result = auditProcessService.findPage (page, queryWrapper);
		return ResponseMessage.OK(result);
	}

	@ApiOperation(value = "查询审核流程列表数据")
	//@PreAuthorize({"erp:audit:auditProcess:listzlc"})
	@GetMapping("listZLC")
	public ResponseEntity<?> listZLC(AuditProcessDTO auditProcessDTO, Page<AuditProcessDTO> page) throws Exception {
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (auditProcessDTO, AuditProcessDTO.class);
		IPage<HashMap> result = auditProcessService.findPageZLC (page,queryWrapper);
		return ResponseMessage.OK(result);
	}


	/**
	 * 根据Id获取审核流程数据
	 */
	//@ApiLog("根据Id获取审核流程数据")
	@ApiOperation(value = "根据Id获取审核流程数据")
	//@PreAuthorize({"erp:audit:auditProcess:view","erp:audit:auditProcess:add","erp:audit:auditProcess:edit"})
	@GetMapping("queryById")
	public ResponseEntity<?> queryById(String id) {
		return ResponseMessage.OK( auditProcessService.findById ( id ) );
	}

	/**
	 * 保存审核流程
	 */
	//@ApiLog("保存审核流程")
	@ApiOperation(value = "保存审核流程")
	//@PreAuthorize({"erp:audit:auditProcess:add","erp:audit:auditProcess:edit"})
	@PostMapping("save")
	public ResponseEntity<?> save(@Valid @RequestBody AuditProcessDTO auditProcessDTO) throws Exception {
	 AuditProcess auditProcess=auditProcessWrapperImpl.toEntity (auditProcessDTO);
		//新增或编辑表单保存
		String FormIdArray[] = auditProcessDTO.getFormId().split(",");
		for (String fid : FormIdArray){
			QueryWrapper query = new QueryWrapper();
			query.eq("form_id", fid);
			List<AuditProcessForm> apfList = auditProcessFormService.list(query);//防止getone时数据库数据不正常多个报错

			if(CollectionUtil.isNotEmpty(apfList)){
				if(StringUtils.isNotEmpty(auditProcessDTO.getId())){
					if(!apfList.get(0).getAuditProcessId().equals(auditProcessDTO.getId())){//如果不是它自己
						return ResponseMessage.ERROR( "一个表单场景只允许对应一个审核主流程配置,如要变更，请将当前要添加表单的对应关系去掉后变更" );
					}
				}else {
					return ResponseMessage.ERROR( "一个表单场景只允许对应一个审核主流程配置,如要变更，请将当前要添加表单的对应关系去掉后变更" );
				}
			}
		}

		if(auditProcessService.saveOrUpdate(auditProcess)){
			String apid = auditProcess.getId();

			String RoleIdArray[] = auditProcessDTO.getAuditor().split(",");
			auditProcessFormService.deleteAuditProcessFormByProcessID(apid);// del ProcessID对应表单
			for (String fid : FormIdArray){//保存对应表单
				AuditProcessForm af = new AuditProcessForm();
				af.setAuditProcessId(apid);
				af.setFormId(fid);
				auditProcessFormService.save(af);
			}

			auditProcessAuditorRoleUserService.deleteAPAuditorRoleUserByProcessID(apid);// del ProcessID对应角色
			for (String fid : RoleIdArray){//保存对应表单
				AuditProcessAuditorRoleUser af = new AuditProcessAuditorRoleUser();
				af.setAuditProcessId(apid);
				af.setAuditorRoleUserId(fid);
				auditProcessAuditorRoleUserService.save(af);
			}

		    return ResponseMessage.OK(auditProcessWrapperImpl.toDTO(auditProcess));
		}{
		    return ResponseMessage.ERROR( "保存审核流程失败" );   
		}
	}


	/**
	 * 删除审核流程
	 */
	//@ApiLog("删除审核流程")
	@ApiOperation(value = "删除审核流程")
	//@PreAuthorize({"erp:audit:auditProcess:del"})
	@DeleteMapping("delete")
	public ResponseEntity<?> delete(String ids) {
		String idArray[] = ids.split(",");
        auditProcessService.removeByIds ( ListUtils.newArrayList ( idArray ) );

		for (String id : idArray) {//logic del 对应表单
			auditProcessFormService.deleteAuditProcessFormByProcessID(id);// del ProcessID对应表单
		}
		for (String id : idArray) {//del ProcessID对应角色
			auditProcessAuditorRoleUserService.deleteAPAuditorRoleUserByProcessID(id);// del ProcessID对应角色
		}

		return ResponseMessage.OK( "删除审核流程成功" );
	}
	
	/**
     * 导出审核流程数据
     *
     * @param auditProcessDTO
     * @param page
     * @param response
     * @throws Exception
     */
    //@ApiLog("导出审核流程数据")
    //@PreAuthorize({"erp:audit:auditProcess:export"})
    /*@GetMapping("export")
    public void exportFile(AuditProcessDTO auditProcessDTO, Page <AuditProcessDTO> page, ExcelOptions options, HttpServletResponse response) throws Exception {
        String fileName = options.getFilename ( );
		QueryWrapper queryWrapper = QueryWrapperGenerator.buildQueryCondition (auditProcessDTO, AuditProcessDTO.class);
        if ( ExportMode.current.equals ( options.getMode ( ) ) ) { // 导出当前页数据
            
        } else if ( ExportMode.selected.equals ( options.getMode ( ) ) ) { // 导出选中数据
            queryWrapper.in ( "a.id", options.getSelectIds () );
        } else { // 导出全部数据
            page.setSize ( -1 );
            page.setCurrent ( 0 );
        }
        List<AuditProcessDTO> result = auditProcessService.findPage ( page, queryWrapper ).getRecords ( );
        EasyExcelUtils.newInstance ( auditProcessService, auditProcessWrapperImpl ).exportExcel ( result,  options.getSheetName ( ), AuditProcessDTO.class, fileName,options.getExportFields (), response );
    }*/

    /**
     * 导入审核流程数据
     *
     * @return
     */
    //@PreAuthorize({"erp:audit:auditProcess:import"})
    /*@PostMapping("import")
    public ResponseEntity importFile(MultipartFile file) throws IOException {
        String result = EasyExcelUtils.newInstance ( auditProcessService, auditProcessWrapperImpl ).importExcel ( file, AuditProcessDTO.class );
        return ResponseMessage.OK(result);
    }
*/
    /**
     * 下载导入审核流程数据模板
     *
     * @param response
     * @return
     */
    //@PreAuthorize({"erp:audit:auditProcess:import"})
    /*@GetMapping("import/template")
    public void importFileTemplate(HttpServletResponse response) throws IOException {
        String fileName = "审核流程数据导入模板.xlsx";
        List<AuditProcessDTO> list = Lists.newArrayList();
        EasyExcelUtils.newInstance ( auditProcessService, auditProcessWrapperImpl ).exportExcel ( list,  "审核流程数据", AuditProcessDTO.class, fileName, null, response );
    }*/


}
